#include "ServerDialog.h"
#include "ui_ServerDialog.h"

ServerDialog::ServerDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ServerDialog)
{
    ui->setupUi(this);
    //当有客户端连接请求到来的时候, 发送newConnection
    connect (&tcpServer, SIGNAL(newConnection()),
             this, SLOT(on_Newconnection()));
}

ServerDialog::~ServerDialog()
{
    delete ui;
}

//点击创建服务器执行的槽函数
void ServerDialog::on_CreateButton_clicked()
{
    //获取端口号
    port = ui->PortEdit->text().toShort();
    //设置监听
    bool res = tcpServer.listen (QHostAddress::Any, port);
    if (res == false) {
        //创建服务器失败
        qDebug ("创建服务器失败");
    }
    qDebug ("创建服务器成功");
    ui->CreateButton->setEnabled(false);
    ui->PortEdit->setEnabled(false);
}

//当客户端和服务器连接时执行的槽函数
void ServerDialog::on_Newconnection (void)
{
    //获取和客户端通信的套接字
    QTcpSocket *tcpClientSocket = tcpServer.nextPendingConnection();
    //将获取到的套接字保存到容器中
    tcpClientList.append(tcpClientSocket);

    connect (tcpClientSocket, SIGNAL(readyRead()),
             this, SLOT(on_ReadyRead()));
}

//当客户端发送消息给服务器时执行的槽函数
void ServerDialog::on_ReadyRead (void)
{
    //判断套接字是否已经断开连接, 如果断开则删除
    for (int i = 0; i < tcpClientList.size(); i++) {
        if (tcpClientList.at(i)->state() == QAbstractSocket::UnconnectedState) {
            tcpClientList.removeAt(i);
        }
    }

    //遍历检查哪个和客户端通信的套接字上面有等待读取的数据
    for (int i = 0; i < tcpClientList.size(); i++) {
        //bytesAvaliable: 获取当前套接字等待读取的字节个数
        if (tcpClientList.at(i)->bytesAvailable()) {
            //读操作
            QByteArray readBuf = tcpClientList.at(i)->readAll();
            //显示读到的信息
            ui->ServerList->addItem(readBuf);
            ui->ServerList->scrollToBottom();
            //转发读到的消息
            sendMessage (readBuf);
        }
    }
}

//转发消息给所有已连接上来的客户端
void ServerDialog::sendMessage (const QByteArray& msg)
{
    for (int i = 0; i < tcpClientList.size(); i++) {
        tcpClientList.at(i)->write(msg);
    }
}









